import os

os.environ["FOR_DISABLE_CONSOLE_CTRL_HANDLER"] = "1"
import signal
import sys
import tkinter as tk

from serial_process import SerialProcess
from settings_window import SettingsWindow


def main_test():
    cleanup_done = False
    root = tk.Tk()
    root.attributes('-fullscreen', True)  # 创建setting界面之前全屏，防止闪烁

    serial_process = SerialProcess()
    settings_window = SettingsWindow(root, serial_process)
    settings_window.update_trial("0/0")

    def cleanup(signal_num=None, frame=None):
        nonlocal cleanup_done
        if not cleanup_done:
            print("执行资源清理...")
            if settings_window.processor:
                settings_window.processor.stop()
            if settings_window.cursor_control:
                settings_window.cursor_control.on_close()
            if settings_window.decoder:
                settings_window.decoder.stop()
            cleanup_done = True
            print("清理完成")
            sys.exit(0)

    signal.signal(signal.SIGINT, cleanup)
    signal.signal(signal.SIGTERM, cleanup)

    def on_escape(event):
        cleanup()

    root.bind("<Escape>", on_escape)

    # 启动事件循环
    root.mainloop()


if __name__ == "__main__":
    main_test()
